#!/usr/bin/perl -w

@P=qw(/usr/bin /usr/sbin /usr/local/bin /bin /sbin /opt/bin);

$VBoxManage=undef;
for (@P) {
	if(-f "$_/VBoxManage" && -x _) {
		$VBoxManage="$_/VBoxManage";last;
	}
}

if(!defined($VBoxManage)) {
	print STDERR "VBoxManage executable not found.\n";
	exit(1);
}

$machine=$ARGV[0];

# Check to see if the machine exists and abort if not.
# If does exist, might already be shutdown.

$r=`$VBoxManage list vms 2>&1`;
if($?>>8) {
	print STDERR "ERROR: Failed to list VirtualBox virtual machines.\n";
	exit(2);
}

my %uuids=();
my %uuids2=();
@L=split(/\n/,$r);
for my $cline (@L[0 .. $#L]) {
	my $x=$cline;
	$x =~ s/^\s+//;
	my @S=split(/\s+/,$x);
	$uuids{$S[1]}=$S[0];
	$uuids2{$S[0]}=$S[1];
}

if(! exists($uuids2{$machine})) {
	print STDERR "ERROR: VBoxManage did not find machine '$machine'.\n";
	exit(2);
}

# Now we can poweroff the machine...
$r=`$VBoxManage controlvm $machine acpipowerbutton 2>&1`;
if($?>>8) {
	print STDERR "ERROR: Failed to send ACPI shutdown signal to VirtualBox virtual machine '$machine'.\n";
	exit(2);
}

exit(0);
